#include "./steam_heat_task.h"
#include "../cfg/app_info.h"
#include "../driver/ctrl.h"
#include "../driver/sensor.h"


namespace task {

SteamHeatTask steamHeatTask;

using namespace driver;
using namespace cfg;

void SteamHeatTask::run() {

    for (;;) {
        switch (m_state) {
        case State::IDLE:
            do_idle();
            break;
        case State::WORK:
            do_work();
            break;
        case State::STOP:
        case State::TIMEOUT:
            do_stop();
            break;
        case State::FAIL:
            do_fail();
            break;
        }
    }
}

void SteamHeatTask::do_idle() {
    for (;;) {
        if (!sensor.is_temp_all_ok()) {
            m_state = State::FAIL;
            break;
        }
        if ((sensor.steam_temp_value() < appInfo->steam_heat_temp) &&
            (sensor.kpa() < appInfo->steam_heat_kpa)) {
            m_state = State::WORK;
            break;
        }
        if (wait(500)) {
            break;
        }
    }
}

void SteamHeatTask::do_stop() { wait(); }

void SteamHeatTask::do_fail() {
    for (;;) {
        if (sensor.is_temp_all_ok()) {
            m_state = State::IDLE;
            break;
        }
        if (wait(500)) {
            break;
        }
    }
}

void SteamHeatTask::do_work() {
    ctrl.open(parts::HEAT_STEAM);
    for (;;) {
        if (!sensor.is_temp_all_ok()) {
            m_state = State::FAIL;
            break;
        }
        if ((sensor.steam_temp_value() > appInfo->steam_heat_temp) ||
            (sensor.kpa() > appInfo->steam_heat_kpa)) {
            m_state = State::IDLE;
            break;
        }
        if (wait(500)) {
            break;
        }
    }
    ctrl.close(parts::HEAT_STEAM);
}

} // namespace task
